package comgame.entities;


import com.almasb.fxgl.dsl.FXGL;
import com.almasb.fxgl.entity.Entity;
import comgame.components.*;
import comgame.components.EquipmentComponent.*;
import comgame.entities.EquipmentEnum.*;
import javafx.util.Duration;

import static com.almasb.fxgl.dsl.FXGL.tpf;

public class Player {
    private Entity entity;
    private HealthComponent health;
    private AnimationComponent animation;
    private AttributeComponent attribute;
    private SkillComponent skill = new SkillComponent();
    private MoneyComponent money = new MoneyComponent(50);
    private BootComponent boot = null;
    private ChestplateComponent chestplate = null;
    private LeggingComponent legging = null;
    private HelmetComponent helmet = null;
    private SwordComponent sword = null;


    public Player(Entity entity) {
        this.entity = entity;
        if (entity != null) {
            this.health = entity.getComponent(HealthComponent.class);
            this.animation = entity.getComponent(AnimationComponent.class);
            this.attribute = entity.getComponent(AttributeComponent.class);
        }
    }

    public void setMaxHealth(int i)
    {
        if (this.health != null && entity != null && entity.isActive()) {
            this.health.setMaxHealth(i);
        }
    }


    // 获取实体
    public Entity getEntity() {
        return entity;
    }

    public boolean isCrit()
    {
        return Math.random() < getCritRate();
    }
    // 添加动画控制方法
    public void attack(Enemy target) {
        if (animation != null && entity != null && entity.isActive() &&
                animation.getCurrentState() != AnimationComponent.AnimState.DEAD) {
            // 检查是否正在攻击中
            if (animation.getCurrentState() == AnimationComponent.AnimState.ATTACKING) {
                System.out.println("玩家正在攻击中，跳过此次攻击");
                return;
            }
            animation.playAttack(target.getEntity().getPosition());
            boolean isCrit = isCrit();
            
            FXGL.getGameTimer().runOnceAfter(() -> {
                double damage = Math.max(1, getAttack() - target.getAttribute().getDefense());
                if (isCrit) {
                    damage *= 1.5;
                }
                target.takeDamage((int) damage);
                if (isCrit) {
                    System.out.println("痛击对手！！！");
                }
            }, Duration.seconds(130*tpf()));
        }
    }

    public void takeDamage(int amount) {
        if (health != null && entity != null && entity.isActive()) {
            health.takeDamage(amount);
            if (animation != null) {
                animation.playHurt();
            }
            if (health.getHealth() <= 0) {
                die();
            }
        }
    }


    public void die() {
        if (animation != null && entity != null && entity.isActive() && !isDead()) {
            animation.playDie();

            // 禁用玩家控制
            entity.setProperty("canControl", false);

            // 移除实体（动画结束后）
            FXGL.runOnce(() -> {
                if (entity != null && entity.isActive()) {
                    entity.removeFromWorld();
                }
            }, Duration.seconds(10.5)); // 匹配死亡动画时长
        }
    }


    public boolean isAttacking() {
        return animation != null && entity != null && entity.isActive() &&
                animation.getCurrentState() == AnimationComponent.AnimState.ATTACKING;
    }

    public boolean isDead() {
        return animation != null && entity != null && entity.isActive() &&
                animation.getCurrentState() == AnimationComponent.AnimState.DEAD;
    }
    public void heal(int amount) {
        if (health != null && entity != null && entity.isActive()) {
            health.heal(amount);
        }
    }

    /**
     * 完全恢复血量到最大值
     */
    public void restoreFullHealth() {
        if (health != null && entity != null && entity.isActive()) {
            health.setHealth(health.getMaxHealth());
        }
    }



    public int getMoney()
    {
        return money.getAmount();
    }
    public double getAttack() {
        // 使用AttributeComponent中已经同步的值
        if (attribute != null) {
            return attribute.getAttack();
        }
        // 如果attribute为null，则重新计算
        double attack = 5 * Math.pow(1.2, skill.getCombatLevel() - 1); // 默认基础攻击力5
        if (sword != null)
            attack += sword.getAttack();
        if (helmet != null)
            attack += helmet.getAttack();
        if (chestplate != null)
            attack += chestplate.getAttack();
        if (legging != null)
            attack += legging.getAttack();
        if (boot != null)
            attack += boot.getAttack();
        return attack;
    }
    public double getDefense() {
        // 使用AttributeComponent中已经同步的值
        if (attribute != null) {
            return attribute.getDefense();
        }
        // 如果attribute为null，则重新计算
        double defense = 3; // 默认基础防御力3
        if (sword != null)
            defense += sword.getDefense();
        if (helmet != null)
            defense += helmet.getDefense();
        if (chestplate != null)
            defense += chestplate.getDefense();
        if (legging != null)
            defense += legging.getDefense();
        if (boot != null)
            defense += boot.getDefense();
        return defense;
    }
    public double getCritRate() {
        // 使用AttributeComponent中已经同步的值
        if (attribute != null) {
            return attribute.getCritRate();
        }
        // 如果attribute为null，则重新计算
        double critRate = 0.05; // 默认基础暴击率5%
        if (sword != null)
            critRate += sword.getCritRate();
        if (helmet != null)
            critRate += helmet.getCritRate();
        if (chestplate != null)
            critRate += chestplate.getCritRate();
        if (legging != null)
            critRate += legging.getCritRate();
        if (boot != null)
            critRate += boot.getCritRate();
        return Math.min(critRate, 1);
    }
    public double getSpeed() {
        // 使用AttributeComponent中已经同步的值
        if (attribute != null) {
            return attribute.getSpeed();
        }
        // 如果attribute为null，则重新计算
        double speed = 2*Math.pow(1.1, skill.getCombatLevel() - 1); // 默认基础速度2
        if (sword != null)
            speed += sword.getSpeed();
        if (helmet != null)
            speed += helmet.getSpeed();
        if (chestplate != null)
            speed += chestplate.getSpeed();
        if (legging != null)
            speed += legging.getSpeed();
        if (boot != null)
            speed += boot.getSpeed();
        return speed;
    }
    public int getHealth()
    {
        return this.health != null ? this.health.getHealth() : 100;
    }

    public int getMaxHealth() {
        return this.health != null ? this.health.getMaxHealth() : 100;
    }

    public int getCombatLevel() {
        return skill.getCombatLevel();
    }

    public int getCombatExp() {
        return skill.getCombatExp();
    }

    public int getCombatExpRequired() {
        return skill.getRequiredExpForLevel(skill.getCombatLevel());
    }

    public void addCombatExpAndLevelUp(int exp) {
        skill.addCombatExp(this, exp);
    }

    public MoneyComponent getMoneyComponent() {
        return money;
    }
    public SkillComponent getSkillComponent() {
        return skill;
    }

    public void setMoney(int amount) {
        money.setAmount(amount);
    }

    public void resetAll() {
        this.skill = new SkillComponent();
        this.skill.setCombatLevel(1);
        this.skill.setCombatExp(0);
        this.money = new MoneyComponent(50);
        this.boot = null;
        this.chestplate = null;
        this.legging = null;
        this.helmet = null;
        this.sword = null;
        // 重置后同步属性到组件
        syncAttributesToComponent();
    }

    public HealthComponent getHealthComponent() {
        return this.health;
    }

    public AttributeComponent getAttribute() {
        return this.attribute;
    }

    public void equipSword(SwordType swordType) {
        this.sword = new SwordComponent(swordType);
        syncAttributesToComponent();
    }
    public void equipHelmet(HelmetType helmetType) {
        this.helmet = new HelmetComponent(helmetType);
        syncAttributesToComponent();
    }
    public void equipChestplate(ChestplateType chestplateType) {
        this.chestplate = new ChestplateComponent(chestplateType);
        syncAttributesToComponent();
    }
    public void equipLegging(LeggingType leggingType) {
        this.legging = new LeggingComponent(leggingType);
        syncAttributesToComponent();
    }
    public void equipBoot(BootType bootType) {
        this.boot = new BootComponent(bootType);
        syncAttributesToComponent();
    }

    // 同步属性到AttributeComponent
    public void syncAttributesToComponent() {
        // 检查实体是否存在且活跃，以及attribute组件是否存在
        if (attribute != null && entity != null && entity.isActive()) {
            try {
                // 直接计算属性值，避免调用getter方法导致无限递归
                double baseAttack = attribute.getBaseAttack();
                double combatLevel = skill.getCombatLevel();
                double attack = baseAttack * Math.pow(1.2, combatLevel - 1);
                
                if (sword != null)
                    attack += sword.getAttack();
                if (helmet != null)
                    attack += helmet.getAttack();
                if (chestplate != null)
                    attack += chestplate.getAttack();
                if (legging != null)
                    attack += legging.getAttack();
                if (boot != null)
                    attack += boot.getAttack();
                
                double defense = attribute.getBaseDefense();
                if (sword != null)
                    defense += sword.getDefense();
                if (helmet != null)
                    defense += helmet.getDefense();
                if (chestplate != null)
                    defense += chestplate.getDefense();
                if (legging != null)
                    defense += legging.getDefense();
                if (boot != null)
                    defense += boot.getDefense();
                
                double critRate = attribute.getBaseCritRate();
                if (sword != null)
                    critRate += sword.getCritRate();
                if (helmet != null)
                    critRate += helmet.getCritRate();
                if (chestplate != null)
                    critRate += chestplate.getCritRate();
                if (legging != null)
                    critRate += legging.getCritRate();
                if (boot != null)
                    critRate += boot.getCritRate();
                critRate = Math.min(critRate, 1);
                
                double speed = attribute.getBaseSpeed();
                if (sword != null)
                    speed += sword.getSpeed();
                if (helmet != null)
                    speed += helmet.getSpeed();
                if (chestplate != null)
                    speed += chestplate.getSpeed();
                if (legging != null)
                    speed += legging.getSpeed();
                if (boot != null)
                    speed += boot.getSpeed();
                
                // 设置到组件
                attribute.setAttack(attack);
                attribute.setDefense(defense);
                attribute.setCritRate(critRate);
                attribute.setSpeed(speed);
            } catch (Exception e) {
                System.out.println("同步属性到组件时出错: " + e.getMessage());
                // 如果出现异常，尝试重新创建玩家实体
                if (entity != null && !entity.isActive()) {
                    System.out.println("玩家实体不活跃，需要重新创建");
                    comgame.scenes.GameScene.recreatePlayerEntity();
                }
            }
        } else {
            System.out.println("无法同步属性：attribute=" + (attribute != null) + 
                             ", entity=" + (entity != null) + 
                             ", entityActive=" + (entity != null && entity.isActive()));
        }
    }

    public void equipByName(String itemName) {
        if (itemName.contains("泰拉棱镜")) {
            equipSword(SwordType.SWORD_TERRAPRISMA);
        } else if (itemName.contains("无头骑士剑")) {
            equipSword(SwordType.SWORD_PUMPKIN);
        } else if (itemName.contains("幽灵剑")) {
            equipSword(SwordType.SWORD_GHOST);
        } else if (itemName.contains("钻石剑")) {
            equipSword(SwordType.SWORD_4);
        } else if (itemName.contains("金剑")) {
            equipSword(SwordType.SWORD_3);
        } else if (itemName.contains("铁剑")) {
            equipSword(SwordType.SWORD_2);
        } else if (itemName.contains("普通剑")) {
            equipSword(SwordType.SWORD_1);
        } else if (itemName.contains("空间之主头盔")) {
            equipHelmet(HelmetType.HELMET_SPACEKING);
        } else if (itemName.contains("幽灵头盔")) {
            equipHelmet(HelmetType.HELMET_GHOST);
        } else if (itemName.contains("钻石头盔")) {
            equipHelmet(HelmetType.HELMET_4);
        } else if (itemName.contains("金头盔")) {
            equipHelmet(HelmetType.HELMET_3);
        } else if (itemName.contains("铁头盔")) {
            equipHelmet(HelmetType.HELMET_2);
        } else if (itemName.contains("普通头盔")) {
            equipHelmet(HelmetType.HELMET_1);
        } else if (itemName.contains("空间之主胸甲")) {
            equipChestplate(ChestplateType.CHESTPLATE_SPACEKING);
        } else if (itemName.contains("幽灵胸甲")) {
            equipChestplate(ChestplateType.CHESTPLATE_GHOST);
        } else if (itemName.contains("喜庆之翼")) {
            equipChestplate(ChestplateType.CHESTPLATE_FESTIVE_WINGS);
        } else if (itemName.contains("钻石胸甲")) {
            equipChestplate(ChestplateType.CHESTPLATE_4);
        } else if (itemName.contains("金胸甲")) {
            equipChestplate(ChestplateType.CHESTPLATE_3);
        } else if (itemName.contains("铁胸甲")) {
            equipChestplate(ChestplateType.CHESTPLATE_2);
        } else if (itemName.contains("普通胸甲")) {
            equipChestplate(ChestplateType.CHESTPLATE_1);
        } else if (itemName.contains("空间之主护腿")) {
            equipLegging(LeggingType.LEGGING_SPACEKING);
        } else if (itemName.contains("幽灵护腿")) {
            equipLegging(LeggingType.LEGGING_GHOST);
        } else if (itemName.contains("钻石护腿")) {
            equipLegging(LeggingType.LEGGING_4);
        } else if (itemName.contains("金护腿")) {
            equipLegging(LeggingType.LEGGING_3);
        } else if (itemName.contains("铁护腿")) {
            equipLegging(LeggingType.LEGGING_2);
        } else if (itemName.contains("普通护腿")) {
            equipLegging(LeggingType.LEGGING_1);
        } else if (itemName.contains("空间之主靴子")) {
            equipBoot(BootType.BOOTS_SPACEKING);
        } else if (itemName.contains("幽灵靴子")) {
            equipBoot(BootType.BOOTS_GHOST);
        } else if (itemName.contains("钻石靴子")) {
            equipBoot(BootType.BOOT_4);
        } else if (itemName.contains("金靴子")) {
            equipBoot(BootType.BOOT_3);
        } else if (itemName.contains("铁靴子")) {
            equipBoot(BootType.BOOT_2);
        } else if (itemName.contains("普通靴子")) {
            equipBoot(BootType.BOOT_1);
        }
        // 注意：这里不需要再次调用syncAttributesToComponent()，因为各个equip方法已经调用了
    }

    public int getFarmingLevel() {
        return skill.getFarming();
    }

    public void addMoney(int i) {
        money.addMoney(i);
    }

    public void deductMoney(int price) {
        money.deductMoney(price);
    }

    public String getEquippedItemName(String type) {
        String result = "";
        switch (type.toLowerCase()) {
            case "sword":
                result = sword != null ? sword.getDisplayName() : "";
                break;
            case "helmet":
                result = helmet != null ? helmet.getDisplayName() : "";
                break;
            case "chestplate":
                result = chestplate != null ? chestplate.getDisplayName() : "";
                break;
            case "legging":
                result = legging != null ? legging.getDisplayName() : "";
                break;
            case "boot":
                result = boot != null ? boot.getDisplayName() : "";
                break;
            default:
                result = "";
        }
        return result;
    }

    public boolean isEquipped(String type) {
        boolean result = false;
        switch (type.toLowerCase()) {
            case "sword":
                result = sword != null;
                break;
            case "helmet":
                result = helmet != null;
                break;
            case "chestplate":
                result = chestplate != null;
                break;
            case "legging":
                result = legging != null;
                break;
            case "boot":
                result = boot != null;
                break;
            default:
                result = false;
        }
        return result;
    }

    public void showEquipmentStatus() {
        System.out.println("[装备状态]");
        System.out.println("武器: " + (sword != null ? sword.getDisplayName() : "无"));
        System.out.println("头盔: " + (helmet != null ? helmet.getDisplayName() : "无"));
        System.out.println("胸甲: " + (chestplate != null ? chestplate.getDisplayName() : "无"));
        System.out.println("护腿: " + (legging != null ? legging.getDisplayName() : "无"));
        System.out.println("靴子: " + (boot != null ? boot.getDisplayName() : "无"));
    }

    public void unequipByType(String type) {
        switch (type.toLowerCase()) {
            case "sword":
                sword = null;
                break;
            case "helmet":
                helmet = null;
                break;
            case "chestplate":
                chestplate = null;
                break;
            case "legging":
                legging = null;
                break;
            case "boot":
                boot = null;
                break;
        }
        syncAttributesToComponent();
    }
}